package com.hellomeng.delegate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//协议1
interface FangwuJiaoYi{
    public void fangwuhetong();
}
//协议2
interface JiazhengFuWu{
    public void jiazhenghetong();
}

//被代理类
class Zuke implements FangwuJiaoYi{
    @Override
    public void fangwuhetong() {
        System.out.println("签房屋合同");
    }
}

//被代理类
class ChanFu implements JiazhengFuWu{
    @Override
    public void jiazhenghetong() {
        System.out.println("签家政合同");
    }
}

//动态代理
class ZhongJieCompany{

    //根据被代理类 生成 代理类
    public static Object getPorxyInstance(Object object){
        //增强方法，当代理对象 代理 被代理对象 去执行 被代理对象内部方法时，最自动执行增强方法
        MyInvocation handler = new MyInvocation(object);
        //JDK提供的方法 参数1：类加载器，参数2：被代理类接口,参数3：增强方法
        return  Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),handler);
    }
}

class MyInvocation implements InvocationHandler{
    //被代理类
    private Object object;
    public  MyInvocation(Object object){
        this.object = object;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("增强内容......");
        method.invoke(object,args);//执行被代理类里的方法
        return null;
    }
}

public class TestDynamicDelegate {
    public static void main(String[] args) {
        Zuke zuke = new Zuke();
        ChanFu chanfu = new ChanFu();
        FangwuJiaoYi zukeProxy = (FangwuJiaoYi)ZhongJieCompany.getPorxyInstance(zuke);
        zukeProxy.fangwuhetong();
        //增强内容......
        //签房屋合同
        JiazhengFuWu chanfuProxy = (JiazhengFuWu)ZhongJieCompany.getPorxyInstance(chanfu);
        chanfuProxy.jiazhenghetong();
        //增强内容......
        //签家政合同

    }
}
